package ua.pp.bizon.cripto.text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Crypto {

    private static final String KEYS_STORE = "keys.store";
    private static final Log LOG = LogFactory.getLog(Crypto.class);

    /**
     * @param args
     */
    public static void main(String[] args) {
        Crypto cripto = new Crypto();
        try {
            System.out.println("input key");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String pass = in.readLine();
            Long authKey = cripto.autorize(pass);
            System.out.println("input line");
            String line = in.readLine();
            System.out.println(cripto.get(line, authKey));
        } catch (IOException e) {
            LOG.fatal(e, e);
        }

    }

    public void remove(String line, Long authKey) {

    };

    public String get(String line, Long authKey) {
        Properties p = new Properties();
        try {
            if (new File(KEYS_STORE).exists()) {
                p.load(new FileReader(new File(KEYS_STORE)));
            }
            return cripto(p.get(line).toString(), authKey);
        } catch (IOException e) {
            LOG.error(e.getCause(), e);
        }
        return null;
    };

    public Long autorize(String pass) {
        return (long) (pass.hashCode()) * Integer.MAX_VALUE + pass.hashCode();
    }

    public void add(String line, String key, Long authKey) {
        Properties p = new Properties();
        try {
            if (new File(KEYS_STORE).exists()) {
                p.load(new FileReader(new File(KEYS_STORE)));
            }
            p.put(line, cripto(key, authKey));
            p.store(new FileWriter(new File(KEYS_STORE)), "");
        } catch (IOException e) {
            LOG.error(e.getCause(), e);
        }
    }

    private String cripto(String key, Long authKey) {
        char[] code = Long.toHexString(authKey).toCharArray();
        char[] from = key.toCharArray();
        char[] to = new char[from.length];
        for (int i = 0, j = 0; i < from.length; i++, j++) {
            if (j == code.length) {
                j = 0;
            }
            to[i] = (char) (from[i] ^ code[j]);
        }
        return new String(to);
    };

}
